/**
 * js
 */
angular.module('mall.order', [])

    .config(['$stateProvider', '$urlRouterProvider',
        function ($stateProvider, $urlRouterProvider) {
            $stateProvider

                .state('placeorder', {
                    url: '/placeorder/:orderid',
                    templateUrl: cmt_mall_templateprefix + '/order/placeorder.html',
                    params: {
                        order: null,
                    },
                    resolve: {
                        userid: ['AuthService', function (AuthService) {
                            return AuthService.ensure_login();
                        }],
                        address_list: ['AddressService', function (AddressService) {
                            var addr = AddressService.alladdress();
                            if (addr.$promise) {
                                return addr.$promise;
                            }
                            return addr;
                        }]
                    },
                    controller: 'PlaceOrderController'
                })

                .state('orderlist', {
                    url: '/orderlist/:active',
                    templateUrl: cmt_mall_templateprefix + '/order/orderlist.html',
                    controller: 'OrderListController'
                })
            ;
        }])

    //订单确认下单控制器
    .controller('PlaceOrderController', ['$scope', '$state', '$stateParams', '$window', 'userid', 'address_list', 'OrderService', 'AuthService', 'ShopcartService',
        function ($scope, $state, $stateParams, $window, userid, address_list, OrderService, AuthService, ShopcartService) {
            //$scope.ent_mallurl = projectBaseUrl;
            var win_width = $(window).width();
            if (getCookie('placeorder') == 'address') {
                placeOrderEnterCss(-win_width, 0, 0, 0);
            } else {
                placeOrderEnterCss(0, 0, win_width, 0);
            }
            $scope.goodscontent = {};
            $scope.orderid = $stateParams.orderid;
            $scope.address_list = address_list;//获取地址列表
            $scope.sel_address = $scope.address_list[0]; //该页选择的收货地址，默认是设置的收货地址
            //选择收货地址
            $scope.select_contact = function (selected) {
                $scope.sel_address = selected;
                $scope.addr_hide();
            }
            $scope.Goback = function () {
                window.history.back();
            }
            var cacheinfo = OrderService.getCacheOreder();
            if ($stateParams.orderid == '' && $stateParams.order != null) {
                OrderService.delcache();//先清除缓存
                OrderService.cacheOrderid($stateParams.orderid);
                cacheinfo = OrderService.cacheOrder($stateParams.order);//缓存订单
            }
            else if (cacheinfo == '' && $stateParams.orderid == '' && $stateParams.order == null) {
                OrderService.delcache();//先清除缓存
                cacheinfo = '';
                $scope.orderid = OrderService.getCacheOrederid();
            }
            if ($stateParams.order != null || cacheinfo != '') {
                if ($stateParams.order == null) {
                    $scope.order = cacheinfo;
                } else {
                    $scope.order = $stateParams.order;
                }
                $scope.deliver_fee = 0; //运费
                $scope.goodscontent.totalprice = 0;
                $scope.shopList = $scope.order;
                var shopList = $scope.order;
                for (var i = 0; i < shopList.length; i++) {
                    $scope.goodscontent.totalprice += shopList[i].goodscontent.totalprice;
                }
                $scope.buyMessage = "";//订单备注
                // 确认下单
                $scope.sure_click = function () {
                    if ($scope.goodscontent.totalprice == 0 || $scope.goodscontent.totalprice == undefined) {
                        alert('订单金额为0')
                    } else if (cacheinfo = !'' && $stateParams.order == null) {
                        $state.go("morepay");
                    } else {
                        var bookRightBlock = document.querySelector('.book-right-block');
                        bookRightBlock.setAttribute('disabled', 'true')
                        $scope.payWait = $('input:radio:checked').val();
                        if (!$scope.sel_address.contactid) {
                            input_alert("请选择收货地址");
                            return;
                        }
                        if ($scope.buyMessage == "") {
                            $scope.buyMessage = "餐谋团订单";
                        }
                        var order = {
                            buyerid: AuthService.getUserid(),
                            buyMessage: $scope.buyMessage,
                            contactid: $scope.sel_address.contactid,
                            type: 0,
                            description: $scope.description,
                            receiverName: $scope.sel_address.name,
                            receiverPhone: $scope.sel_address.phone,
                            receiverZip: $scope.sel_address.zipcode,
                            receiverAddress: $scope.sel_address.address,
                            orderDetails: []
                        };
                        for (var i = 0; i < shopList.length; i++) {
                            var goods_list = shopList[i].list;
                            for (var j = 0; j < goods_list.length; j++) {
                                var goods = goods_list[j].goods;
                                for (var k = 0; k < goods.length; k++) {
                                    var good = goods[k];
                                    order.orderDetails.push({
                                        shopid: shopList[i].shopid,
                                        goodsid: good.goodsid,
                                        skuid: 0,
                                        fee: good.price * good.buycount,
                                        num: good.buycount
                                    });
                                }
                            }
                        }
                        if ($scope.payWait == 4) {
                            order.type = 4;
                            OrderService.createOrder(order).$promise.then(function (data) {
                                for (var k = 0; k < shopList.length; k++) {
                                    ShopcartService.cleanByShopId(shopList[k].shopid);
                                }
                                if (data.sumPrice < 0.001) {
                                    input_alert("订单创建失败", 1000);
                                    bookRightBlock.removeAttribute('disabled', 'true');
                                    setTimeout(function () {
                                        $window.location.href = projectBaseUrl;
                                    }, 1000);
                                }
                                //
                                else {
                                    $state.go("orderlist", {active: 1});
                                }
                            }, function (error) {
                                input_alert("创建订单失败：" + JSON.stringify(error), 1000);
                                bookRightBlock.removeAttribute('disabled', 'true');
                                setTimeout(function () {
                                    $window.location.href = projectBaseUrl;
                                }, 1000);
                            });
                        }
                        else {
                            console.log(order);
                            OrderService.createOrder(order).$promise.then(function (data) {
                                for (var k = 0; k < shopList.length; k++) {
                                    ShopcartService.cleanByShopId(shopList[k].shopid);
                                }
                                if (data.sumPrice < 0.001) {
                                    bookRightBlock.removeAttribute('disabled', 'true');
                                    input_alert("订单创建失败", 1000);
                                    setTimeout(function () {
                                        //$window.location.href = projectBaseUrl;
                                    }, 1000);
                                }
                                //
                                else {
                                    $state.go("morepay", {order: data});
                                }
                            }, function (error) {
                                bookRightBlock.removeAttribute('disabled', 'true');
                                input_alert("创建订单失败：" + JSON.stringify(error), 1000);
                                setTimeout(function () {
                                    //$window.location.href = projectBaseUrl;
                                }, 1000);

                            });
                        }
                    }
                }
            }

            //管理收货地址
            $scope.increased = function () {
                $window.location.href = projectBaseUrl + "address";
            }
            $scope.addr_show = function () {
                placeOrderEnterCss(-win_width, 200, 0, 200);
                setCookie('placeorder', 'address', 30);
            }
            $scope.addr_hide = function () {
                placeOrderEnterCss(0, 200, win_width, 200);
                setCookie('placeorder', 'order', 30);
            }
        }
    ])
    //待收货控制器
    .controller('OrderListController',['$scope', '$stateParams','$state','ShopcartService','OrderService',
        function ($scope, $stateParams,$state, ShopcartService,OrderService) {
            console.log("111");
            dismiss();
            ShopcartService.synchronizationStorage();
            $scope.mall_enturl = projectBaseUrl;//回跳地址
            $scope.allorders = [];
            $scope.waitpayorder = [];
            $scope.waitdeliveryorder = [];
            $scope.orderdo = [];
            $scope.completeorder = [];
            /*$scope.Paystate = 1;*/
            $scope.mall_ucurl = projectBaseUrl;
            //全部订单
            $scope.page = {
                num: 5,
                n: 1,
            }
            //待付款
            $scope.paystate0 = {
                paystate: 0,
                status: 0,
                num: 5,
                n: 1,
            }
            //待发货
            $scope.paystate1 = {
                paystate: 1,
                status: 0,
                num: 5,
                n: 1,
            }
            //待收货
            $scope.status1 = {
                status: 1,
                n: 1,
                num: 5,
            }

            //已完成待评价
            $scope.status2 = {
                status: 2,
                n: 1,
                num: 5,
            }
            //所有订单
            $scope.all = function () {
                OrderService.selectOrders($scope.page).$promise.then(function (data) {
                    for (var i = 0; i < data.length; i++) {
                        $scope.allorders.push(data[i])
                    }
                    var order_length = $scope.page.n * $scope.page.num;
                    if (order_length > $scope.allorders.length) {
                        $scope.load0 = true;
                    }
                    else {
                        $scope.load0 = false;
                    }
                    if ($scope.allorders.length != 0) {
                        $scope.flat0 = true;
                    } else {
                        $scope.flat0 = false;
                    }
                })
            }

            //待付款
            $scope.waitpay = function () {
                OrderService.selectOrders($scope.paystate0).$promise.then(function (data) {
                    for (var i = 0; i < data.length; i++) {
                        $scope.waitpayorder.push(data[i]);
                    }
                    var order_length = $scope.paystate0.n * $scope.paystate0.num;
                    if (order_length > $scope.waitpayorder.length) {
                        $scope.load1 = true;
                    }
                    else {
                        $scope.load1 = false;
                    }
                    if ($scope.waitpayorder.length != 0) {
                        $scope.flat1 = true;
                    } else {
                        $scope.flat1 = false;
                    }
                })
            }
            //待发货
            $scope.waitdelivery = function () {
                OrderService.selectOrders($scope.paystate1).$promise.then(function (data) {
                    for (var i = 0; i < data.length; i++) {
                        $scope.waitdeliveryorder.push(data[i]);
                    }
                    var order_length = $scope.paystate1.n * $scope.paystate1.num;
                    if (order_length > $scope.waitdeliveryorder.length) {
                        $scope.load2 = true;
                    }
                    else {
                        $scope.load2 = false;
                    }
                    if ($scope.waitdeliveryorder.length != 0) {
                        $scope.flat2 = true;
                    } else {
                        $scope.flat2 = false;
                    }
                })
            }
            //待收货
            $scope.doing = function () {
                OrderService.selectOrders($scope.status1).$promise.then(function (data) {
                    for (var i = 0; i < data.length; i++) {
                        $scope.orderdo.push(data[i]);
                    }
                    var order_length = $scope.status1.n * $scope.status1.num;
                    if (order_length > $scope.orderdo.length) {
                        $scope.load3 = true;
                    }
                    else {
                        $scope.load3 = false;
                    }
                    if ($scope.orderdo.length != 0) {
                        $scope.flat3 = true;
                    } else {
                        $scope.flat3 = false;
                    }
                })
            }

            //待评价
            $scope.completed = function () {
                OrderService.selectOrders($scope.status2).$promise.then(function (data) {
                    for (var i = 0; i < data.length; i++) {
                        $scope.completeorder.push(data[i]);
                    }
                    var order_length = $scope.status2.n * $scope.status2.num;
                    if (order_length > $scope.completeorder.length) {
                        $scope.load4 = true;
                    }
                    else {
                        $scope.load4 = false;
                    }
                    if ($scope.completeorder.length != 0) {
                        $scope.flat4 = true;
                    } else {
                        $scope.flat4 = false;
                    }
                })
            }

            //确认收货
            $scope.sure_finish = function (order) {
                $(".contain-item").fadeIn();
                $scope.finish = function () {
                    order.status = 2;
                    OrderService.updateorder(order, function (data) {
                        /*OrderService.postuserpoint(order, function () {
                            //上传积分
                        })*/
                        delete order;
                        var indextodelete = -1;
                        for (var i = 0; i < $scope.orderdo.length; i++) {
                            if ($scope.orderdo[i].orderid == order.orderid) {
                                //从数组中删除这个id的�??
                                indextodelete = i;
                                break;
                            }
                        }
                        if (indextodelete >= 0) {
                            $scope.orderdo.splice(indextodelete, 1);
                        }
                        $(".contain-item").fadeOut();
                        input_alert("订单已确认收货，可在待评价页面查看")
                    }, function () {
                    });
                }

            }

            //继续支付
            $scope.immpay = function (orderid) {
                $state.go('morepay', {orderid: orderid});
            }
            //根据订单完成状态不同进行不同操作
            $scope.differStatus = function (order) {
                if (order.paystate != 1) {
                    $state.go('morepay', {orderid: order.orderid});
                } else if (order.status == 1) {
                    $scope.sure_finish(order);
                } else if (order.status == 2) {
                    input_alert("该功能尚未开放");
                }
            }
            //评价
            $scope.evaluate = function () {
                input_alert("该功能尚未开放");
            }
            //取消订单
            $scope.sure_cancel = function (order) {
                $(".contain-item1").fadeIn();
                $scope.cancel = function () {
                    order.status = 4;
                    OrderService.updateorder(order, function () {
                        order.status = 4;
                        for (var i = 0; i < $scope.allorders.length; i++) {
                            if ($scope.allorders[i].orderid == update.orderid) {
                                $scope.allorders[i].status = 4;
                                break;
                            }
                        }

                        $(".contain-item1").fadeOut();
                        input_alert("订单已取消", 1000);
                    });
                }
            }
            //删除订单
            $scope.sure_delete = function (order, orderslist) {
                $(".contain-item2").fadeIn();
                $scope.deleteOrder = function () {
                    OrderService.deleteOrder(order.orderid, function () {
                        var indextodelete = -1;
                        for (var i = 0; i < $scope.allorders.length; i++) {
                            if ($scope.allorders[i].orderid == order.orderid) {
                                //从数组中删除这个id的�??
                                indextodelete = i;
                                break;
                            }
                        }
                        for (var i = 0; i < orderslist.length; i++) {
                            if (orderslist[i].orderid == order.orderid) {
                                //从数组中删除这个id的�??
                                indextodelete = i;
                                break;
                            }
                        }
                        if (indextodelete >= 0) {
                            $scope.allorders.splice(indextodelete, 1);
                            orderslist.splice(indextodelete, 1);
                        }
                        $(".contain-item2").fadeOut();
                        input_alert("订单已删除", 1000);
                    });
                }
            }
            //初始进入获取数据库数据
            $scope.initialization = function (status) {
                if (status == 0 && $scope.allorders.length == 0) {
                    $scope.all();
                }
                else if (status == 1 && $scope.waitpayorder.length == 0) {
                    $scope.waitpay();
                }
                else if (status == 2 && $scope.waitdeliveryorder.length == 0) {
                    $scope.waitdelivery();
                }
                else if (status == 3 && $scope.orderdo.length == 0) {
                    $scope.doing();
                }
                else if (status == 4 && $scope.completeorder.length == 0) {
                    $scope.completed();
                }
            }
            $scope.active = $stateParams.active;
            //不同入口显示不同状态
            if ($scope.active == 1) {
                //待支付
                order_active(".wait_pay", "#wait_pay");
                $scope.initialization(1);
            } else if ($scope.active == 2) {
                //待发货
                order_active(".wait_delivery", "#wait_delivery");
                $scope.initialization(2);
            } else if ($scope.active == 3) {
                //待收货
                order_active(".processing", "#processing");
                $scope.initialization(3);
            } else if ($scope.active == 4) {
                //完成的订单
                order_active(".finish", "#finish");
                $scope.initialization(4);
            } else {
                //全部订单
                order_active(".all", "#all");
                $scope.initialization(0);
            }
            //滚动自动加载更多
            $(window).scroll(function () {
                var scrollTop = $(this).scrollTop();
                var scrollHeight = $(document).height();
                var windowHeight = $(this).height();
                if (scrollTop + windowHeight >= scrollHeight - 50) {
                    if ($('#all').hasClass('active')) {
                        $scope.page.n++;
                        $scope.all();
                    }
                    if ($('#wait_pay').hasClass('active')) {
                        $scope.paystate0.n++;
                        $scope.waitpay();
                    }
                    if ($('#wait_delivery').hasClass('active')) {
                        $scope.paystate1.n++;
                        $scope.waitdelivery();
                    }
                    if ($('#processing').hasClass('active')) {
                        $scope.status1.n++;
                        $scope.doing();
                    }
                    if ($('#finish').hasClass('active')) {
                        $scope.status2.n++;
                        $scope.completed();
                    }
                }
            })
        }])
;
